<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Upload extends Controller {
    public function action_uploadCT() {
        $ctdir = realpath("CT");
        
        $p_id = $_POST['p_id'];
        $c_id = $_POST['c_id'];
        $description = $_POST['ct_description'];
        
        $today = getdate();
        $day = $today["mday"];
        $month = $today["mon"];
        $year = $today["year"];

        $uploadpath = $ctdir."/".$p_id;
        if(!file_exists($uploadpath)){
            mkdir($uploadpath);
        }

        $uploadpath = $uploadpath."/"."$year";
        if(!file_exists($uploadpath)){
            mkdir($uploadpath);
        }

        $uploadpath = $uploadpath."/"."$month";
        if(!file_exists($uploadpath)){
            mkdir($uploadpath);
        }

        $sql = "SELECT * FROM ct_scan where p_id=".$p_id." and c_id=".$c_id;
        $query = Database::instance()->query(Database::SELECT, $sql, FALSE)->as_array();

        $index = count($query);
        
        $filename = $day."_".$c_id."_".$index.".jpg";
        DB::insert('ct_scan',array('p_id','c_id','path','year','month','filename','description','upload_date','original_filename'))
                    ->values(array($p_id,$c_id,$uploadpath,$year,$month,$filename,$description,DB::expr('NOW()'),$_FILES["upload"]["name"]))->execute();
                      
        Upload::save($_FILES["upload"], $filename, $uploadpath);

        $this->request->redirect('patient/ctscan?c_id='.$c_id.'&p_id='.$p_id);
    }
}